package lq.cloud.studyserversystem.configure;

import lq.cloud.studyserversystem.properties.StudyServerSystemProperties;
import lq.common.handler.StudyAccessDeniedHandler;
import lq.common.handler.StudyAuthExceptionEntryPoint;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @program: cloud-study
 * @description: 资源服务器配置类
 * <p>
 * 添加资源路径免认证:
 * 1.在配置里面添加免认证路径
 * 2.configure(HttpSecurity http) 方法里面将免配置路径拆分为数组
 * 3.使用.antMatchers("免认证数组").permitAll()添加到资源免认证
 * @author: LQ
 * @create: 2020-09-23 15:39
 */
@Configuration
@EnableResourceServer
public class StudyServerSystemResourceServerConfigure extends ResourceServerConfigurerAdapter {

    @Autowired
    private StudyAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private StudyAuthExceptionEntryPoint authExceptionEntryPoint;

    @Autowired
    private StudyServerSystemProperties properties;

    /**
     * 配置study-server-system的请求认证
     * 以下配置表示所有请求都需要进行认证,只有通过服务器发放的令牌才能够访问
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        String[] anonUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ",");

        http.csrf().disable().requestMatchers().antMatchers("/**").and().authorizeRequests().antMatchers(anonUrls).permitAll().antMatchers("/**").authenticated();
    }

    /**
     * 重写异常处理
     *
     * @param resource
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resource) {
        resource.authenticationEntryPoint(authExceptionEntryPoint).accessDeniedHandler(accessDeniedHandler);
    }
}
